package com.warmheart.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.warmheart.base.entity.LoginUser;
import com.warmheart.base.entity.Operator;
import com.warmheart.base.session.SessionLocalUtils;
import com.warmheart.core.enums.DELETED;

public class OperatorUtil {

    private static final Logger logger = LoggerFactory.getLogger(OperatorUtil.class);

    public static <T> void addOper(T entity) {
        LoginUser loginUser = null;
        Operator operator = SessionLocalUtils.getOperator();
        if (operator != null) {
            loginUser = operator.getLoginUser();
        }
        try {
            preAdd(entity, loginUser);
            preUpdate(entity, loginUser);
        } catch (Exception e) {
            // 记录异常堆栈信息
            logger.error("操作添加实体类通用信息异常：" + e.getMessage(), e);
        }
    }

    public static <T> void updateOper(T entity) {
        LoginUser loginUser = null;
        Operator operator = SessionLocalUtils.getOperator();
        if (operator != null) {
            loginUser = operator.getLoginUser();
        }
        try {
            preUpdate(entity, loginUser);
        } catch (Exception e) {
            // 记录异常堆栈信息
            logger.error("操作编辑实体类通用信息异常：" + e.getMessage(), e);
        }
    }

    private static <T> void preAdd(T t, LoginUser loginUser) throws Exception {
        // 设置新建人与新建日期
        ClassReflectUtil.setFieldValue(t, "cstCreate", DateUtils.getDate());
        if (loginUser != null) {
            ClassReflectUtil.setFieldValue(t, "createBy", loginUser.getUserId());
        }
        // 设置删除标记位为正常
        ClassReflectUtil.setFieldValue(t, "delFlag", DELETED.DELETED_NO.getValue());
    }

    private static <T> void preUpdate(T t, LoginUser loginUser) throws Exception {
        // 设置更新人与更新日期
        ClassReflectUtil.setFieldValue(t, "cstModify", DateUtils.getDate());
        if (loginUser != null) {
            ClassReflectUtil.setFieldValue(t, "updateBy", loginUser.getUserId());
        }
    }

}
